<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList()">
          <a-radio-button v-for="item of statusList" :key="item.id" :value="item.id"> {{ item.name }} </a-radio-button>
        </a-radio-group>

        <div style="display: flex">
          <a-button type="primary" style="margin-right: 10px" @click="visible = true">+ 新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('remove', '2')">批量删除</a-menu-item>
              <a-menu-item @click="handleAll('change', '1')" v-if="queryParam.status != '1'">批量开启</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')" v-if="queryParam.status != '0'">批量关闭</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-table
        :row-key="record => record.id"
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        :pagination="{
          total: this.totalCount,
          showSizeChanger: true,
          onChange: this.getList,
          onShowSizeChange: this.paginationSizeChange
        }"
        :data-source="list"
        :loading="loading"
        :columns="columns"
      >
        <span slot="rule" slot-scope="text, record">
          {{ record.type === '0' ? record.times : '下单后' + record.days + '天' }}
        </span>

        <span slot="switch" slot-scope="text, record">
          <a-switch
            :checked="record.status === '1' ? true : false"
            checked-children="开"
            un-checked-children="关"
            @change="handleItem('change', record)"
          />
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleItem('edit', record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleItem('remove', record)" size="small">删除</a-button>
        </span>
      </a-table>

      <a-modal :title="getTitle" :visible="visible" @ok="onSubmit" width="800px" @cancel="visible = false">
        <a-form-model
          :loading="loading"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="规则名称" prop="name">
            <a-input v-model="form.name"></a-input>
          </a-form-model-item>
          <a-form-model-item label="时效设置" prop="type">
            <a-radio-group v-model="form.type">
              <a-radio value="0">固定时间</a-radio>
              <a-radio value="1">下单后</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="天数设置" prop="times" v-if="form.type === '0'">
            <a-date-picker
              v-model="form.times"
              :showTime="true"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择结束时间"
              style="width:100%;"
            />
          </a-form-model-item>
          <a-form-model-item label="天数设置" prop="days" v-if="form.type === '1'">
            <div class="flex">
              <a-input-number style="flex:1;" v-model="form.days" :min="1" :precision="0" />
              <div class="slot">天</div>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { List, Save, Status } from '@/api/setting/distributionRules'

export default {
  data() {
    return {
      queryParam: {
        status: '-1'
      },

      labelCol: { span: 4 },
      wrapperCol: { span: 14 },

      form: {
        name: '',
        type: '0',
        times: '',
        days: ''
      },

      rules: {
        name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择时效设置', trigger: 'change' }],
        times: [{ required: true, message: '请设置天数', trigger: 'change' }],
        days: [{ required: true, message: '请设置天数', trigger: 'blur' }]
      },

      list: [],
      selectedRowKeys: [],

      totalCount: 0,
      pageSize: 10,
      pageNo: 1,
      loading: false,
      visible: false,

      columns: [
        {
          title: '规则名称',
          dataIndex: 'name',
          key: 'name',
          ellipsis: true
        },
        {
          title: '配送规则',
          scopedSlots: { customRender: 'rule' }
        },
        {
          title: '是否开启',
          scopedSlots: { customRender: 'switch' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 150
        }
      ],

      statusList: [
        { id: '-1', name: '全部' },
        { id: '1', name: '已开启' },
        { id: '0', name: '已关闭' }
      ]
    }
  },

  computed: {
    getTitle() {
      return this.form.id ? '编辑规则' : '新增规则'
    }
  },

  watch: {
    visible(e) {
      if (!e) {
        this.resetForm()
      }
    }
  },

  methods: {
    // 分页器页数修改回调
    paginationSizeChange(current, size) {
      this.pageSize = size
      this.getList(current)
    },

    getList(pageNo = 1) {
      this.loading = true
      let { queryParam, pageSize } = this
      List({
        ...queryParam,
        pageNo,
        pageSize
      })
        .then(res => {
          this.loading = false

          if (!res.code) {
            this.pageNo = pageNo
            this.list = res.data.data
            return
          }

          this.$message.error(res.msg)
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 批量操作
    handleAll(type, status) {
      let selectedRowKeys = this.selectedRowKeys

      if (!selectedRowKeys.length) {
        return this.$message.error('请至少选择一条选项！')
      }

      selectedRowKeys = selectedRowKeys.join(',')
      switch (type) {
        case 'remove':
          this.Status(selectedRowKeys, status)
          break
        case 'change':
          this.Status(selectedRowKeys, status)
          break
      }
    },

    handleItem(type, scope) {
      switch (type) {
        case 'edit':
          this.form = {
            name: scope.name,
            type: scope.type,
            times: scope.times,
            days: scope.days,
            id: scope.id
          }
          this.visible = true
          break

        case 'remove':
          this.Status(scope.id, '2')
          break

        case 'change':
          this.Status(scope.id, scope.status === '1' ? '0' : '1')
          break
      }
    },

    Status(ids, status) {
      // 0.禁用 1.启用 2.删除
      Status({
        ids,
        status
      }).then(res => {
        if (!res.code) {
          this.$message.success('操作成功')
          this.selectedRowKeys = []
          this.getList()
          return
        }

        this.$message.error(res.msg)
      })
    },

    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let { form } = this

          this.loading = true
          Save(form).then(res => {
            if (!res.code) {
              this.$message.success('操作成功！')
              this.visible = false
              this.loading = false

              this.form = {
                name: '',
                type: '0',
                times: '',
                days: ''
              }

              this.getList()
              return
            }

            this.$message.error(res.msg)
          })
        } else {
          return false
        }
      })
    },

    resetForm() {
      this.$refs.ruleForm.resetFields()
    }
  },

  created() {
    this.getList()
  }
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;

  .slot {
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    height: 32px;
    width: 32px;
    background: rgba(247, 247, 247, 1);
    text-align: center;
  }
}
</style>
